/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EditProfilePatient.java
 *
 * Created on Jul 24, 2011, 3:21:33 PM
 */
package admin;

import generalCode.Connectionsql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Hoai An
 */
public class PatientForm extends javax.swing.JFrame {

    private boolean isUpdate = false;
    private ArrayList<PatientDTO> listPatient = new ArrayList<PatientDTO>();
    Vector<String> columnNames;

    {
        columnNames = new Vector<String>();
        columnNames.add("Id");
        columnNames.add("FullName");
        columnNames.add("Address");
        columnNames.add("Phone Number");
        columnNames.add("Email");
        columnNames.add("Sex");
    }

    /** Creates new form EditProfilePatient */
    public PatientForm() {
        initComponents();
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        initData();
        this.setTitle("Management all patient");
//        try {
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//            SwingUtilities.updateComponentTreeUI(this);
//        } catch (Exception ex) {
//            Logger.getLogger(PatientForm.class.getName()).log(Level.SEVERE, null, ex);
//            ex.printStackTrace();
//        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btGroupSex = new javax.swing.ButtonGroup();
        pnMain = new javax.swing.JPanel();
        pnTop = new javax.swing.JPanel();
        lbID = new javax.swing.JLabel();
        lbFullname = new javax.swing.JLabel();
        lbAddress = new javax.swing.JLabel();
        lbPhoneNumber = new javax.swing.JLabel();
        lbEmail = new javax.swing.JLabel();
        lbSex = new javax.swing.JLabel();
        tfID = new javax.swing.JTextField();
        tfFullname = new javax.swing.JTextField();
        tfAddress = new javax.swing.JTextField();
        tfEmail = new javax.swing.JTextField();
        btAdd = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();
        tfPhoneNumber = new javax.swing.JFormattedTextField();
        rbMale = new javax.swing.JRadioButton();
        rbFemale = new javax.swing.JRadioButton();
        btReset = new javax.swing.JButton();
        pnBottom = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbProfile = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        tfSeach = new javax.swing.JTextField();
        btSeach = new javax.swing.JButton();
        cbxSeach = new javax.swing.JComboBox();
        lbTitle = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        pnTop.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Patient Infomation", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        pnTop.setLayout(null);

        lbID.setText("ID:");
        pnTop.add(lbID);
        lbID.setBounds(70, 30, 20, 14);

        lbFullname.setText("Fullname:(*)");
        pnTop.add(lbFullname);
        lbFullname.setBounds(40, 70, 70, 14);

        lbAddress.setText("Address:(*)");
        pnTop.add(lbAddress);
        lbAddress.setBounds(40, 100, 70, 14);

        lbPhoneNumber.setText("Phone Number:");
        pnTop.add(lbPhoneNumber);
        lbPhoneNumber.setBounds(320, 30, 100, 20);

        lbEmail.setText("Email:");
        pnTop.add(lbEmail);
        lbEmail.setBounds(370, 70, 50, 14);

        lbSex.setText("Sex:");
        pnTop.add(lbSex);
        lbSex.setBounds(380, 110, 40, 14);

        tfID.setEditable(false);
        pnTop.add(tfID);
        tfID.setBounds(140, 30, 160, 20);
        pnTop.add(tfFullname);
        tfFullname.setBounds(140, 70, 160, 20);
        pnTop.add(tfAddress);
        tfAddress.setBounds(140, 110, 160, 20);
        pnTop.add(tfEmail);
        tfEmail.setBounds(420, 70, 160, 20);

        btAdd.setText("Add");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });
        pnTop.add(btAdd);
        btAdd.setBounds(200, 150, 90, 23);

        btDelete.setText("Delete");
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteActionPerformed(evt);
            }
        });
        pnTop.add(btDelete);
        btDelete.setBounds(310, 150, 90, 23);

        try {
            tfPhoneNumber.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        pnTop.add(tfPhoneNumber);
        tfPhoneNumber.setBounds(420, 30, 160, 20);

        btGroupSex.add(rbMale);
        rbMale.setSelected(true);
        rbMale.setText("Male");
        pnTop.add(rbMale);
        rbMale.setBounds(430, 110, 60, 23);

        btGroupSex.add(rbFemale);
        rbFemale.setText("Female");
        pnTop.add(rbFemale);
        rbFemale.setBounds(500, 110, 70, 23);

        btReset.setText("Reset");
        btReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btResetActionPerformed(evt);
            }
        });
        pnTop.add(btReset);
        btReset.setBounds(420, 150, 90, 23);

        tbProfile.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "ID", "Fullname", "Address", "PhoneNumber", "Email", "Sex"
            }
        ));
        tbProfile.setColumnSelectionAllowed(true);
        tbProfile.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tbProfile.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbProfileMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbProfile);
        tbProfile.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jLabel1.setText("Seach with:");

        btSeach.setText("Seach");
        btSeach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSeachActionPerformed(evt);
            }
        });

        cbxSeach.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "      ID", "   Name" }));

        org.jdesktop.layout.GroupLayout pnBottomLayout = new org.jdesktop.layout.GroupLayout(pnBottom);
        pnBottom.setLayout(pnBottomLayout);
        pnBottomLayout.setHorizontalGroup(
            pnBottomLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnBottomLayout.createSequentialGroup()
                .add(pnBottomLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, pnBottomLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 700, Short.MAX_VALUE))
                    .add(pnBottomLayout.createSequentialGroup()
                        .add(27, 27, 27)
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(cbxSeach, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 65, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(58, 58, 58)
                        .add(tfSeach, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 142, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(46, 46, 46)
                        .add(btSeach)))
                .addContainerGap())
        );
        pnBottomLayout.setVerticalGroup(
            pnBottomLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, pnBottomLayout.createSequentialGroup()
                .addContainerGap()
                .add(pnBottomLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(btSeach)
                    .add(tfSeach, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(cbxSeach, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 20, Short.MAX_VALUE)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 218, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        lbTitle.setFont(new java.awt.Font("Tahoma", 1, 18));
        lbTitle.setText("Edit Patient Profile");

        org.jdesktop.layout.GroupLayout pnMainLayout = new org.jdesktop.layout.GroupLayout(pnMain);
        pnMain.setLayout(pnMainLayout);
        pnMainLayout.setHorizontalGroup(
            pnMainLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnMainLayout.createSequentialGroup()
                .addContainerGap()
                .add(pnMainLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, pnMainLayout.createSequentialGroup()
                        .add(lbTitle)
                        .add(211, 211, 211))
                    .add(pnTop, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 720, Short.MAX_VALUE)
                    .add(pnBottom, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        pnMainLayout.setVerticalGroup(
            pnMainLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnMainLayout.createSequentialGroup()
                .addContainerGap()
                .add(lbTitle)
                .add(18, 18, 18)
                .add(pnTop, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 204, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(pnBottom, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(pnMain, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(pnMain, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        String id = this.tfID.getText();
        String name = this.tfFullname.getText();
        String address = this.tfAddress.getText();
        String phone = this.tfPhoneNumber.getText();
        String email = this.tfEmail.getText();
        boolean male = this.rbMale.isSelected();
        if (name.equals("") || address.equals("")) {
            JOptionPane.showMessageDialog(this, "Please! Complete information required!");
        } else {
            if (!isUpdate) {
                addPatient(name, address, phone, email, male);
            } else {
                updatePatient(id, name, address, phone, email, male);
                this.resetForm();
                this.isUpdate = false;
                this.btAdd.setText("Add");
            }
        }
    }//GEN-LAST:event_btAddActionPerformed

    private void tbProfileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbProfileMouseClicked
        int selectedRow = this.tbProfile.getSelectedRow();
        String idStr = (String) this.tbProfile.getValueAt(selectedRow, 0);
        String name = (String) this.tbProfile.getValueAt(selectedRow, 1);
        String address = (String) this.tbProfile.getValueAt(selectedRow, 2);
        String phone = (String) this.tbProfile.getValueAt(selectedRow, 3);
        String email = (String) this.tbProfile.getValueAt(selectedRow, 4);
        String sex = (String) this.tbProfile.getValueAt(selectedRow, 5);
        fillData(idStr, name, address, phone, email, sex);
        this.btAdd.setText("Update");
        this.isUpdate = true;
    }//GEN-LAST:event_tbProfileMouseClicked

    private void btDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteActionPerformed
        String Id = this.tfID.getText();
        int response = JOptionPane.showConfirmDialog(null, "Are you sure delete it?", "Confirm",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.YES_OPTION) {
            deletePatient(Id);
        }
    }//GEN-LAST:event_btDeleteActionPerformed

    private void btResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btResetActionPerformed
        resetForm();
        initData();
    }//GEN-LAST:event_btResetActionPerformed

    private void btSeachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSeachActionPerformed
        String inputSeach = this.tfSeach.getText();
        int isSelected = this.cbxSeach.getSelectedIndex();
        if (inputSeach.equals("")) {
            JOptionPane.showMessageDialog(this, "Input seacch is not blank! Please try again!");
        } else {
            Seach(inputSeach, isSelected);
        }
    }//GEN-LAST:event_btSeachActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btDelete;
    private javax.swing.ButtonGroup btGroupSex;
    private javax.swing.JButton btReset;
    private javax.swing.JButton btSeach;
    private javax.swing.JComboBox cbxSeach;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbAddress;
    private javax.swing.JLabel lbEmail;
    private javax.swing.JLabel lbFullname;
    private javax.swing.JLabel lbID;
    private javax.swing.JLabel lbPhoneNumber;
    private javax.swing.JLabel lbSex;
    private javax.swing.JLabel lbTitle;
    private javax.swing.JPanel pnBottom;
    private javax.swing.JPanel pnMain;
    private javax.swing.JPanel pnTop;
    private javax.swing.JRadioButton rbFemale;
    private javax.swing.JRadioButton rbMale;
    private javax.swing.JTable tbProfile;
    private javax.swing.JTextField tfAddress;
    private javax.swing.JTextField tfEmail;
    private javax.swing.JTextField tfFullname;
    private javax.swing.JTextField tfID;
    private javax.swing.JFormattedTextField tfPhoneNumber;
    private javax.swing.JTextField tfSeach;
    // End of variables declaration//GEN-END:variables

    private void resetForm() {
        this.tfID.setText("");
        this.tfAddress.setText("");
        this.tfFullname.setText("");
        this.rbMale.setSelected(true);
        this.tfEmail.setText("");
        this.tfPhoneNumber.setText("");
        this.btAdd.setText("Add");
    }

    private void addPatient(String name, String address, String phone, String email, boolean male) {
        Connectionsql db = Connectionsql.newInstance();
        if (validateInput()) {
            try {
                int gen = (male ? 1 : 0);
                String sql = "insert into patient(fullname, address, phonenumber, email, sex) values('"
                        + name
                        + "', '" + address
                        + "', '" + phone
                        + "', '" + email
                        + "', '" + gen
                        + "');";
                System.out.println(sql);
                if (db.update(sql)) {
                    JOptionPane.showMessageDialog(this, "Add new patient successfully!");

                    initData();
                }
                db.closeConn();
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "ERROR: " + ex.getMessage());
            }


        }

    }

    private void updatePatient(String id, String name, String address, String phone, String email, boolean male) {
        Connectionsql db = Connectionsql.newInstance();
        if (validateInput()) {
            try {
                int gen = (male ? 1 : 0);
                String sql = "update patient set fullname=?, address=?, phonenumber=?, email=?, sex=? where patientid = ?";
                Object[] arr = new Object[]{name, address, phone, email, gen, id};
                System.out.println(sql);
                if (db.updateWithParam(sql, arr)) {
                    JOptionPane.showMessageDialog(this, "Update patient successfully!");
                    initData();
                }
                db.closeConn();
            } catch (SQLException ex) {
                Logger.getLogger(PatientForm.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }
        }
    }

    private void deletePatient(String id) {
        try {
            String sql = "delete patient where patientid=?;";
            Object[] arr = new Object[]{id};
            Connectionsql conn = Connectionsql.newInstance();
            if (conn.updateWithParam(sql, arr)) {
                JOptionPane.showMessageDialog(this, "Delete new patient successfully!");
                initData();
                conn.closeConn();
            }
        } catch (SQLException ex) {
            Logger.getLogger(PatientForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void initData() {
        initTable(null);
    }

    public void initTable(String sql) {
        listPatient = new ArrayList<PatientDTO>();
        this.tbProfile.removeAll();
        try {
            //load db
            Connectionsql db = Connectionsql.newInstance();
            if (sql == null) {
                sql = "select * from patient order by patientid";
            }
            ResultSet rs = db.query(sql);
            String sex = "";
            while (rs.next()) {
                if (rs.getBoolean("sex")) {
                    sex = "male";
                } else {
                    sex = "female";
                }
                listPatient.add(new PatientDTO(rs.getInt("patientid"), rs.getString("fullname"),
                        rs.getString("address"), rs.getString("phonenumber"),
                        rs.getString("email"), sex));
            }
            db.closeConn();
            //show table
            Vector<Vector<String>> data = new Vector<Vector<String>>();
            for (int i = 0; i < listPatient.size(); i++) {
                Vector<String> v = new Vector<String>();
                v.add(listPatient.get(i).getId() + "");
                v.add(listPatient.get(i).getName());
                v.add(listPatient.get(i).getAddress());
                v.add(listPatient.get(i).getPhone());
                v.add(listPatient.get(i).getEmail());
                v.add(listPatient.get(i).getSex());
                data.add(v);

            }
            tbProfile.setModel(new DefaultTableModel(data, columnNames));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void fillData(String id, String name, String address, String phone, String email, String sex) {

        this.tfID.setText(id);
        this.tfFullname.setText(name);
        this.tfAddress.setText(address);
        this.tfPhoneNumber.setText(phone);
        this.tfEmail.setText(email);
        System.out.println(sex);
        if ("male".equals(sex)) {
            this.rbMale.setSelected(true);
        } else {
            this.rbFemale.setSelected(true);
        }
    }

    private boolean validateInput() {
        if (tfFullname.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in Fullname!");
            return false;
        } else if (tfAddress.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in Address!");
            return false;
        }
        return true;
    }

    private void Seach(String inputSeach, int isSelected) {
        String sql="";
        if (isSelected == 0) {
            sql = "select * from patient where patientid like " + inputSeach + "order by patientid";
        } else if (isSelected == 1) {
            sql = sql = "select * from patient where fullname like '%" + inputSeach + "%'order by patientid";
        }
        initTable(sql);
    }
}
